package com.dewod.producesales.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.dewod.producesales.R;
import com.dewod.producesales.adapter.DeliveryAdapter;
import com.dewod.producesales.model.request.EnableOrderQuery;
import com.dewod.producesales.model.response.StoreSalesContract;
import com.dewod.producesales.utils.request.RequestApiUtil;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.textfield.TextInputEditText;

import java.util.ArrayList;
import java.util.List;

public class DeliverActivity extends AppCompatActivity {

    private TextInputEditText orderNoInput;
    private Button searchButton;
    private RecyclerView recyclerView;
    private DeliveryAdapter adapter;

    private TabLayout tabLayout;

    private final EnableOrderQuery query = new EnableOrderQuery();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_deliver);

        query.setLogisticsStatus(0);

        // 初始化视图
        bindViews();

        // 初始化适配器
        initAdapter();

        // 设置点击监听器
        setupClickListeners();

        queryData();

        LocalBroadcastManager.getInstance(this)
                .registerReceiver(updateReceiver, new IntentFilter("ACTION_DATA_UPDATED"));

    }

    private void bindViews() {
        orderNoInput = findViewById(R.id.orderNo_input);
        searchButton = findViewById(R.id.search_button);
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        tabLayout = findViewById(R.id.tabLayout);
    }

    private void initAdapter() {
        adapter = new DeliveryAdapter(new ArrayList<>());
        recyclerView.setAdapter(adapter);
    }

    private void setupClickListeners() {
        orderNoInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String orderNo = s.toString();
                query.setOrderNum(orderNo);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        searchButton.setOnClickListener(v -> {
            String orderNo = orderNoInput.getText().toString();
            query.setOrderNum(orderNo);
            this.queryData();
        });

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                query.setLogisticsStatus(tab.getPosition());
                queryData();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private BroadcastReceiver updateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i("updateReceiver", "收到数据更新广播");
            queryData(); // 执行刷新逻辑
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(updateReceiver);
    }

    /**
     * 数据查询并展示
     */
    private void queryData() {
        // 模拟数据
        RequestApiUtil.getEnableOrder(query, responseData -> {
            this.runOnUiThread(() -> {
                if(responseData.getSuccess()){
                    List<StoreSalesContract> contracts = JSON.parseArray(JSON.toJSONString(responseData.getData()), StoreSalesContract.class) ;
                    if(adapter == null ){
                        adapter = new DeliveryAdapter(contracts);
                        recyclerView.setAdapter(adapter);
                    }else{
                        adapter.updateData( contracts);
                    }
                }else {
                    Toast.makeText(this, "查询失败 " + responseData.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
        });

    }
}
